/* *****************************************************************************
 * JFab (http://code.google.com/p/jfab)
 * Copyright (c) 2011 JFab.org
 * Admin jfab@jeffreythompson.net
 *
 * See the file "LICENSE.txt" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 * *****************************************************************************/

package org.jfab.core.comparator;

import java.util.Comparator;

import org.jfab.core.model.CGMethodDeclaration;
import org.jfab.core.model.CGParameter;
import org.jfab.core.model.CGType;

/**
 * Provides a code generator method comparator.
 */
public class CGMethodDeclarationComparator implements
        Comparator<CGMethodDeclaration>
{
    /**
     * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
     */
    @Override
    public int compare(final CGMethodDeclaration object1,
            final CGMethodDeclaration object2)
    {
        int answer = -1;

        if (object1 == object2)
        {
            answer = 0;
        }
        else if (object1 == null)
        {
            answer = 1;
        }
        else if (object2 == null)
        {
            answer = -1;
        }
        else
        {
            final String name1 = object1.getName();
            final String name2 = object2.getName();

            if (name1 == name2)
            {
                answer = 0;
            }
            else if (name1 == null)
            {
                answer = 1;
            }
            else if (name2 == null)
            {
                answer = -1;
            }
            else
            {
                answer = name1.compareTo(name2);
            }

            if (answer == 0)
            {
                final String methodSignature1 = createMethodSignature(object1);
                final String methodSignature2 = createMethodSignature(object2);
                answer = methodSignature1.compareTo(methodSignature2);
            }
        }

        return answer;
    }

    /**
     * @param cgMethod Code generator method.
     * 
     * @return a representation of a method signature.
     */
    private String createMethodSignature(final CGMethodDeclaration cgMethod)
    {
        final StringBuilder sb = new StringBuilder();

        sb.append(cgMethod.getName());

        for (final CGParameter cgParameter : cgMethod.getParameters())
        {
            final CGType type = cgParameter.getType();
            sb.append(type.getName());
        }

        return sb.toString();
    }
}
